import express from 'express';
import { createServer } from 'http';
import { createServer as createHttpsServer } from 'https';
import { Server } from 'socket.io';
import fs from 'fs';
import path from 'path';
import cors from 'cors';
import helmet from 'helmet';
import { config, validateConfig, isDevelopment } from './config';
import {
  ServerToClientEvents,
  ClientToServerEvents,
  InterServerEvents,
  SocketData,
  DeviceInfo,
  VoiceTextData,
  SmartInputError,
  ApiResponse,
  ServerStats,
  RegisteredDevice
} from './types';
import DeviceManager from './services/DeviceManager';
import { WebSocketService } from './services/WebSocketService';
import { SSEService } from './services/SSEService';
import PairingManager from './services/PairingManager';
import SpeechService from './services/SpeechService';
import { HybridConnectionManager } from './services/HybridConnectionManager';
const jwt = require('jsonwebtoken')
const SECRET = 'smartinput-demo-secret'
const Database = require('better-sqlite3');
const db = new Database('smartinput.db');
const { v4: uuidv4 } = require('uuid');

// 初始化表
// 用户表
// 设备表
// 验证码表
db.exec(`
CREATE TABLE IF NOT EXISTS users (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  userId TEXT UNIQUE,
  phone TEXT UNIQUE,
  username TEXT UNIQUE,
  password TEXT,
  nickname TEXT
);
CREATE TABLE IF NOT EXISTS devices (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  deviceId TEXT UNIQUE,
  userId TEXT,
  name TEXT,
  online INTEGER,
  hardwareFingerprint TEXT UNIQUE
);
CREATE TABLE IF NOT EXISTS sms_codes (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  phone TEXT,
  code TEXT,
  expiresAt INTEGER
);
`);

class SmartInputServer {
  private app: express.Application;
  private server: ReturnType<typeof createServer> | ReturnType<typeof createHttpsServer>;
  private io: Server<ClientToServerEvents, ServerToClientEvents, InterServerEvents, SocketData>;
  private deviceManager: DeviceManager;
  private pairingManager: PairingManager;
  private wsService: WebSocketService;
  private sseService: SSEService;
  private hybridManager: HybridConnectionManager;
  private stats: ServerStats;
  private startTime: number;
  private speechService: any; // 用于存储SpeechService实例
  private pairingRequestLocks: Map<string, number> = new Map(); // 幂等锁

  constructor() {
    // 验证配置
    validateConfig();

    this.app = express();

    // 检查是否存在HTTPS证书
    const projectRoot = process.cwd().includes('/server') ? process.cwd().replace('/server', '') : process.cwd();
    const certPath = path.join(projectRoot, 'certs', 'cert.pem');
    const keyPath = path.join(projectRoot, 'certs', 'key.pem');
    const useHttps = fs.existsSync(certPath) && fs.existsSync(keyPath);

    if (useHttps) {
      const httpsOptions = {
        key: fs.readFileSync(keyPath),
        cert: fs.readFileSync(certPath)
      };
      this.server = createHttpsServer(httpsOptions, this.app);
      console.log('🔒 HTTPS服务器已启用');
    } else {
      this.server = createServer(this.app);
      console.log('🔓 HTTP服务器已启用');
    }

    this.io = new Server<ClientToServerEvents, ServerToClientEvents, InterServerEvents, SocketData>(
      this.server,
      {
        cors: {
          origin: "*", // 允许所有来源，便于开发测试
          methods: ["GET", "POST"]
        }
      }
    );

    this.deviceManager = new DeviceManager();
    this.pairingManager = new PairingManager(this.deviceManager);
    this.deviceManager.setPairingManager(this.pairingManager);
    this.wsService = new WebSocketService(this.io);
    this.sseService = new SSEService();
    // 注入连接池
    this.deviceManager.setWebSocketService(this.wsService);
    this.deviceManager.setSSEService(this.sseService);
    this.hybridManager = new HybridConnectionManager(this.io);
    this.startTime = Date.now();
    this.stats = this.initializeStats();

    this.setupMiddleware();
    this.setupRoutes();
    this.setupHybridHandlers();
    this.setupSocketHandlers();
    this.setupErrorHandlers();
  }

  /**
   * 获取 Express 应用实例（用于测试）
   */
  public getApp(): express.Application {
    return this.app;
  }

  /**
   * 获取设备管理器实例（用于测试）
   */
  public getDeviceManager(): DeviceManager {
    return this.deviceManager;
  }

  /**
   * 获取配对管理器实例（用于测试）
   */
  public getPairingManager(): PairingManager {
    return this.pairingManager;
  }

  private initializeStats(): ServerStats {
    return {
      uptime: 0,
      connectedDevices: 0,
      totalConnections: 0,
      messagesProcessed: 0,
      pairingAttempts: 0,
      successfulPairings: 0,
      errors: 0,
      lastActivity: Date.now()
    };
  }

  private setupMiddleware(): void {
    if (!isDevelopment) {
      this.app.use(helmet());
    }

    // 使用更开放的CORS策略以进行开发测试
    this.app.use(cors({
      origin: "*", // 允许任何来源
      methods: ["GET", "POST", "PUT", "DELETE"],
      allowedHeaders: ["Content-Type", "Authorization"],
    }));
    this.app.use(express.json({ limit: '10mb' }));
    this.app.use(express.urlencoded({ extended: true }));

    // 静态文件服务 - 提供 React 构建产物静态资源
    this.app.use('/assets', express.static(path.join(__dirname, '..', 'public', 'assets')));

    // 管理页面入口 - 返回 React 构建产物 index.html
    this.app.get('/admin', (req, res) => {
      const indexPath = path.join(__dirname, '..', 'public', 'index.html');
      res.sendFile(indexPath, (err) => {
        if (err) {
          console.error('Error serving admin page:', err);
          res.status(500).send('Error loading admin page');
        }
      });
    });

    // 请求日志
    this.app.use((req, res, next) => {
      console.log(`${new Date().toISOString()} ${req.method} ${req.path}`);
      next();
    });
  }

  private setupHybridHandlers(): void {
    // 设置混合连接管理器的事件处理器
    this.hybridManager.on('device:register', (data: any) => {
      this.handleDeviceRegister(data);
    });

    this.hybridManager.on('pairing:generate-code', (data: any) => {
      this.handleGeneratePairingCode(data);
    });

    this.hybridManager.on('pairing:use-code', (data: any) => {
      this.handleUsePairingCode(data);
    });

    this.hybridManager.on('voice:send-text', (data: any) => {
      this.handleVoiceSendText(data);
    });

    this.hybridManager.on('voice:recognize', (data: any) => {
      this.handleVoiceRecognize(data);
    });

    this.hybridManager.on('voice:stream/start', (data: any) => {
      this.handleVoiceStreamStart(data);
    });

    this.hybridManager.on('voice:stream/data', (data: any) => {
      this.handleVoiceStreamData(data);
    });

    this.hybridManager.on('voice:stream/end', (data: any) => {
      this.handleVoiceStreamEnd(data);
    });

    this.hybridManager.on('device:get-list', (data: any) => {
      this.handleGetDeviceList(data);
    });

    this.hybridManager.on('device:pair', (data: any) => {
      this.handleDevicePair(data);
    });

    this.hybridManager.on('device:get-pairing-status', (data: any) => {
      this.handleGetPairingStatus(data);
    });
  }

  private setupRoutes(): void {
    // 健康检查
    this.app.get('/health', (req, res) => {
      const response: ApiResponse = {
        success: true,
        data: {
          status: 'ok',
          timestamp: new Date().toISOString(),
          uptime: Date.now() - this.startTime,
          connectedDevices: this.deviceManager.getDeviceCount(),
          version: '1.0.0'
        },
        timestamp: Date.now()
      };
      res.json(response);
    });

    // 获取服务器统计信息
    this.app.get('/api/stats', (req, res) => {
      const deviceStats = this.deviceManager.getDevicesStatus();
      const pairingStats = this.pairingManager.getStats();

      const response: ApiResponse = {
        success: true,
        data: {
          server: {
            ...this.stats,
            uptime: Date.now() - this.startTime
          },
          devices: deviceStats,
          pairing: pairingStats
        },
        timestamp: Date.now()
      };
      res.json(response);
    });

    // 获取设备列表
    this.app.get('/api/devices', (req, res) => {
      const devices = this.deviceManager.getOnlineDevices().map(device => ({
        id: device.id,
        type: device.type,
        name: device.name,
        capabilities: device.capabilities,
        isOnline: device.isOnline,
        lastSeen: device.lastSeen
      }));

      const response: ApiResponse = {
        success: true,
        data: devices,
        timestamp: Date.now()
      };
      res.json(response);
    });

    // 获取所有注册设备（含离线）
    this.app.get('/api/devices/all', (req, res) => {
      const devices = this.deviceManager.getAllDevices().map(device => ({
        id: device.id,
        type: device.type,
        name: device.name,
        capabilities: device.capabilities,
        isOnline: device.isOnline,
        lastSeen: device.lastSeen
      }));

      const response: ApiResponse = {
        success: true,
        data: devices,
        timestamp: Date.now()
      };
      res.json(response);
    });

    // 获取配对关系列表
    this.app.get('/api/pairings', (req, res) => {
      const pairings = this.pairingManager.getActivePairingRelationships().map(pairing => ({
        id: pairing.id,
        device1: {
          id: pairing.device1Id,
          name: pairing.device1Name,
          type: pairing.device1Type
        },
        device2: {
          id: pairing.device2Id,
          name: pairing.device2Name,
          type: pairing.device2Type
        },
        createdAt: pairing.createdAt,
        lastActivity: pairing.lastActivity,
        isActive: pairing.isActive
      }));

      const response: ApiResponse = {
        success: true,
        data: pairings,
        timestamp: Date.now()
      };
      res.json(response);
    });

    // 获取设备的配对关系
    this.app.get('/api/devices/:deviceId/pairings', (req, res) => {
      const deviceId = req.params.deviceId;
      const pairings = this.pairingManager.getDevicePairingRelationships(deviceId).map(pairing => ({
        id: pairing.id,
        device1: {
          id: pairing.device1Id,
          name: pairing.device1Name,
          type: pairing.device1Type
        },
        device2: {
          id: pairing.device2Id,
          name: pairing.device2Name,
          type: pairing.device2Type
        },
        createdAt: pairing.createdAt,
        lastActivity: pairing.lastActivity,
        isActive: pairing.isActive
      }));

      const response: ApiResponse = {
        success: true,
        data: pairings,
        timestamp: Date.now()
      };
      res.json(response);
    });

    // SSE连接端点
    this.app.get('/api/sse/connect', (req, res) => {
      const deviceId = req.query.deviceId as string;
      const clientId = req.query.clientId as string;
      const userAgent = req.get('User-Agent');
      
      if (!deviceId || !clientId) {
        res.status(400).json({ error: 'Missing deviceId or clientId' });
        return;
      }

      this.hybridManager.getSSEService().connect(clientId, deviceId, res, userAgent);
    });

    // 设备状态SSE
    this.app.get('/api/sse/device/:deviceId', (req, res) => {
      const deviceId = req.params.deviceId;
      const clientId = `device-${deviceId}-${Date.now()}`;
      const userAgent = req.get('User-Agent');
      
      this.hybridManager.getSSEService().connect(clientId, deviceId, res, userAgent);
    });

    // 设备注册API
    this.app.post('/api/devices/register', (req, res) => {
      const deviceInfo = req.body;
      const deviceId = this.deviceManager.registerDeviceWithServerGeneratedId('api', deviceInfo);
      
      res.json({
        success: true,
        deviceId,
        message: 'Device registered successfully'
      });
    });

    // 语音识别API
    this.app.post('/api/voice/recognize', async (req, res) => {
      const { audioData, language, deviceId } = req.body;
      
      try {
        if (!this.speechService) {
          this.speechService = new SpeechService();
        }

        const result = await this.speechService.speechToText(audioData, { language });
        
        // 通过混合管理器发送结果到配对设备
        this.hybridManager.sendMessage({
          id: this.generateMessageId(),
          type: 'voice:result',
          data: {
            success: true,
            text: result.text,
            confidence: result.confidence,
            language,
            deviceId,
            timestamp: Date.now()
          },
          timestamp: Date.now(),
          source: 'api',
          target: deviceId
        });

        res.json({
          success: true,
          text: result.text,
          confidence: result.confidence
        });
      } catch (error) {
        res.status(500).json({
          success: false,
          error: error instanceof Error ? error.message : 'Unknown error'
        });
      }
    });

    // 配对相关API
    this.app.post('/api/pairing/generate-code', async (req, res) => {
      const { deviceId } = req.body;
      
      try {
        const pairingCode = await this.pairingManager.generatePairingCode(deviceId);
        res.json({
          success: true,
          code: pairingCode.code,
          qrCodeUrl: pairingCode.qrCodeUrl,
          expiresAt: pairingCode.expiresAt
        });
      } catch (error) {
        res.status(400).json({
          success: false,
          error: error instanceof Error ? error.message : 'Unknown error'
        });
      }
    });

    // 文字发送API
    this.app.post('/api/text/send', (req, res) => {
      const { text, deviceId, targetDeviceId } = req.body;
      
      this.hybridManager.sendMessage({
        id: this.generateMessageId(),
        type: 'text:receive',
        data: {
          text,
          fromDeviceId: deviceId,
          timestamp: Date.now()
        },
        timestamp: Date.now(),
        source: 'api',
        target: targetDeviceId
      });

      res.json({ success: true });
    });

    // 混合连接统计API
    this.app.get('/api/hybrid/stats', (req, res) => {
      const stats = this.hybridManager.getConnectionStats();
      res.json({
        success: true,
        data: stats,
        timestamp: Date.now()
      });
    });

    // 断开配对关系
    this.app.delete('/api/pairings/:pairingId', (req, res) => {
      const pairingId = req.params.pairingId;
      const pairings = this.pairingManager.getAllPairingRelationships();
      const pairing = pairings.find(p => p.id === pairingId);

      if (!pairing) {
        res.status(404).json({
          success: false,
          message: '配对关系不存在',
          timestamp: Date.now()
        });
        return;
      }

      const success = this.pairingManager.disconnectPairing(pairing.device1Id, pairing.device2Id);

      const response: ApiResponse = {
        success: true,
        data: { pairingId },
        timestamp: Date.now()
      };
      res.json(response);
    });

    // 测试输入框API
    this.app.post('/api/test-input', (req, res) => {
      try {
        const { text } = req.body;

        if (!text || typeof text !== 'string') {
          res.status(400).json({
            success: false,
            message: '缺少文本内容',
            timestamp: Date.now()
          });
          return;
        }

        console.log('🧪 收到测试输入:', text);

        // 这里可以添加测试逻辑，比如转发到所有在线设备
        const onlineDevices = this.deviceManager.getOnlineDevices();
        console.log(`📤 测试输入将转发到 ${onlineDevices.length} 个在线设备`);

        const response: ApiResponse = {
          success: true,
          data: {
            message: '测试输入已接收',
            text,
            timestamp: Date.now(),
            onlineDevices: onlineDevices.length
          },
          timestamp: Date.now()
        };

        res.json(response);
      } catch (error) {
        console.error('测试输入处理失败:', error);
        res.status(500).json({
          success: false,
          message: '服务器内部错误',
          timestamp: Date.now()
        });
      }
    });

    // HTTP配对API - 生成配对码
    this.app.post('/api/pairing/generate', async (req: express.Request, res: express.Response) => {
      try {
        const { deviceId, deviceType, deviceName } = req.body;

        if (!deviceId || !deviceType) {
          res.status(400).json({
            success: false,
            message: 'Missing required fields: deviceId, deviceType',
            timestamp: Date.now()
          });
          return;
        }

        // 检查设备是否已注册，如果没有则先注册
        let device = this.deviceManager.getDevice(deviceId);

        if (!device) {
          console.log(`设备 ${deviceId} 未找到，创建临时注册`);

          // 创建临时Socket ID
          const tempSocketId = 'http-temp-' + Date.now();

          // 创建设备信息，使用客户端提供的deviceId
          const deviceInfo = {
            type: deviceType as 'mobile' | 'browser',
            name: deviceName || 'Unknown Device',
            capabilities: deviceType === 'browser' ? {
              canReceiveText: true,
              canSendVoice: false,
              canGenerateQR: true,
              canScanQR: false
            } : {
              canSendVoice: true,
              canReceiveText: false,
              canGenerateQR: false,
              canScanQR: true
            }
          };

          // 使用客户端提供的deviceId注册设备
          try {
            device = this.deviceManager.registerDeviceWithId(tempSocketId, deviceId, deviceInfo);
            console.log(`临时设备注册成功: ${deviceId} (保持原始ID)`);
          } catch (error) {
            console.error(`临时设备注册失败: ${deviceId}`, error);
            throw new SmartInputError('Failed to register temporary device', 'DEVICE_REGISTRATION_FAILED', 500);
          }
        }

        this.stats.pairingAttempts++;
        const result = await this.pairingManager.generatePairingCode(deviceId);

        res.json({
          success: true,
          code: result.code,
          qrCode: result.qrCodeUrl,
          expiresAt: result.expiresAt,
          timestamp: Date.now()
        });
      } catch (error) {
        this.stats.errors++;
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({
          success: false,
          message: errorMessage,
          timestamp: Date.now()
        });
      }
    });

    // HTTP设备注册API - 服务端生成ID
    this.app.post('/api/device/register', async (req: express.Request, res: express.Response) => {
      try {
        const { type, name, capabilities, hardwareFingerprint } = req.body;

        if (!type) {
          res.status(400).json({
            success: false,
            message: 'Missing required field: type',
            timestamp: Date.now()
          });
          return;
        }

        // 创建临时Socket ID
        const tempSocketId = 'http-temp-' + Date.now();

        // 准备设备信息
        const deviceInfo = {
          type: type as 'mobile' | 'browser' | 'desktop',
          name: name && name.trim() ? name : (type === 'browser' ? 'Browser Device' : 'Mobile Device'),
          capabilities: capabilities, // 让DeviceManager处理默认capabilities
          hardwareFingerprint
        };

        // 使用服务端生成ID注册设备
        let device: RegisteredDevice;
        if (hardwareFingerprint) {
          device = this.deviceManager.registerDeviceWithServerGeneratedId(tempSocketId, deviceInfo);
          console.log(`HTTP API设备注册成功（硬件指纹）: ${device.id}`);
        } else {
          device = this.deviceManager.registerDeviceWithServerGeneratedId(tempSocketId, deviceInfo);
          console.log(`HTTP API设备注册成功（服务端生成）: ${device.id}`);
        }

        res.json({
          success: true,
          deviceId: device.id,
          message: `设备注册成功: ${device.name}`,
          timestamp: Date.now()
        });
      } catch (error) {
        this.stats.errors++;
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({
          success: false,
          message: errorMessage,
          timestamp: Date.now()
        });
      }
    });

    // 删除注册设备
    (this.app as any).delete('/api/devices/:deviceId', (req: express.Request, res: express.Response) => {
      const deviceId = req.params.deviceId as string;
      try {
        const success = this.deviceManager.deleteDevice(deviceId);
        if (!success) {
          return res.status(404).json({ success: false, message: '设备不存在', timestamp: Date.now() });
        }
        return res.json({ success: true, message: '设备已删除', timestamp: Date.now() });
      } catch (e) {
        return res.status(500).json({ success: false, message: '删除失败', timestamp: Date.now() });
      }
    });

    // 获取指定设备信息（放在 /api/devices/all 之前，避免路由冲突）
    (this.app as any).get('/api/devices/:deviceId', (req: express.Request, res: express.Response) => {
      const deviceId = req.params.deviceId || '';
      const device = this.deviceManager.getDevice(deviceId);
      if (!device) {
        return res.status(404).json({ success: false, message: '设备不存在', timestamp: Date.now() });
      }
      // 获取配对信息
      const pairings = this.pairingManager.getDevicePairingRelationships(deviceId) || [];
      // 当前会话（如有）
      const currentSession = pairings.length > 0 ? pairings[0]?.id : null;
      const response = {
        success: true,
        data: {
          device,
          pairings,
          currentSession
        },
        timestamp: Date.now()
      };
      return res.json(response);
    });

    // 错误处理
    this.app.use('*', (req, res) => {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'NOT_FOUND',
          message: `Route ${req.originalUrl} not found`,
          timestamp: Date.now()
        }
      };
      res.status(404).json(response);
    });

    // 发送验证码
    this.app.post('/api/send-sms', (req, res) => {
      const { phone } = req.body;
      if (!/^1\d{10}$/.test(phone)) {
        return res.status(400).json({ message: '手机号格式错误' });
      }
      const code = Math.floor(100000 + Math.random() * 900000).toString();
      const expiresAt = Date.now() + 5 * 60 * 1000;
      db.prepare('INSERT INTO sms_codes (phone, code, expiresAt) VALUES (?, ?, ?)').run(phone, code, expiresAt);
      console.log(`验证码发送到 ${phone}: ${code}`);
      res.json({ success: true });
    });

    // 手机号验证码登录
    this.app.post('/api/login/sms', (req, res) => {
      const { phone, code } = req.body;
      const record = db.prepare('SELECT * FROM sms_codes WHERE phone = ? ORDER BY id DESC LIMIT 1').get(phone);
      if (!record || record.code !== code || record.expiresAt < Date.now()) {
        return res.status(400).json({ message: '验证码错误或已过期' });
      }
      let user = db.prepare('SELECT * FROM users WHERE phone = ?').get(phone);
      if (!user) {
        const userId = 'u_' + phone;
        db.prepare('INSERT INTO users (userId, phone, nickname) VALUES (?, ?, ?)').run(userId, phone, '用户' + phone.slice(-4));
        user = db.prepare('SELECT * FROM users WHERE phone = ?').get(phone);
      }
      const token = jwt.sign({ userId: user.userId, phone: user.phone, nickname: user.nickname }, SECRET, { expiresIn: '7d' });
      res.json({ userId: user.userId, phone: user.phone, nickname: user.nickname, token });
    });

    // 用户名密码登录
    this.app.post('/api/login/password', (req, res) => {
      const { username, password } = req.body;
      const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
      if (!user || user.password !== password) {
        return res.status(400).json({ message: '用户名或密码错误' });
      }
      const token = jwt.sign({ userId: user.userId, username: user.username, nickname: user.nickname }, SECRET, { expiresIn: '7d' });
      res.json({ userId: user.userId, username: user.username, nickname: user.nickname, token });
    });

    // 认证中间件
    function auth(req, res, next) {
      const authHeader = req.headers['authorization'];
      if (!authHeader) return res.status(401).json({ message: '未登录' });
      const token = authHeader.split(' ')[1];
      try {
        req.user = jwt.verify(token, SECRET);
        next();
      } catch {
        res.status(401).json({ message: 'token无效' });
      }
    }

    // 获取当前用户的设备列表
    this.app.get('/api/devices', auth, (req, res) => {
      const userId = req.user.userId;
      const userDevices = db.prepare('SELECT * FROM devices WHERE userId = ?').all(userId);
      res.json({ devices: userDevices });
    });

    // 同步文字到设备
    this.app.post('/api/devices/:deviceId/sync-text', auth, (req, res) => {
      const { deviceId } = req.params;
      const { text } = req.body;
      if (!text) return res.status(400).json({ message: '缺少同步内容' });
      const device = db.prepare('SELECT * FROM devices WHERE deviceId = ?').get(deviceId);
      if (!device) return res.status(404).json({ message: '设备不存在' });
      if (device.userId !== req.user.userId) return res.status(403).json({ message: '无权操作该设备' });
      // 推送到设备（如有 socket.io 可实现）
      console.log(`用户${req.user.userId} 同步到设备${deviceId}:`, text);
      res.json({ success: true });
    });

    // 设备注册接口（指纹唯一性）
    this.app.post('/api/devices/register', auth, (req, res) => {
      const { hardwareFingerprint, name } = req.body;
      const userId = req.user.userId;
      if (!hardwareFingerprint) {
        return res.status(400).json({ message: '缺少设备指纹' });
      }
      // 查找是否已有该指纹的设备
      let device = db.prepare('SELECT * FROM devices WHERE hardwareFingerprint = ?').get(hardwareFingerprint);
      if (!device) {
        const deviceId = uuidv4();
        db.prepare('INSERT INTO devices (deviceId, userId, name, online, hardwareFingerprint) VALUES (?, ?, ?, 1, ?)')
          .run(deviceId, userId, name || '新设备', hardwareFingerprint);
        device = db.prepare('SELECT * FROM devices WHERE deviceId = ?').get(deviceId);
      } else {
        // 更新归属用户和设备名
        db.prepare('UPDATE devices SET userId = ?, name = ? WHERE deviceId = ?')
          .run(userId, name || device.name, device.deviceId);
      }
      res.json({ deviceId: device.deviceId, name: device.name });
    });
  }

  private setupSocketHandlers(): void {
    this.io.on('connection', (socket) => {
      console.log(`新设备连接: ${socket.id}`);
      this.stats.totalConnections++;
      this.updateConnectedDevicesCount();

      // 设备注册
      socket.on('device:register', async (deviceInfo: any) => {
        try {
          let device: RegisteredDevice;
          
          console.log('info', `device:register => received deviceInfo: ${JSON.stringify(deviceInfo)}`);
          
          // 新的注册逻辑：服务端生成ID
          if (deviceInfo.hardwareFingerprint) {
            // 使用硬件指纹，服务端生成或查找ID
            device = this.deviceManager.registerDeviceWithServerGeneratedId(socket.id, deviceInfo);
            console.log('info', `📱 使用硬件指纹注册，服务端生成ID: ${device?.id || 'unknown'}`);
          } else if (deviceInfo.deviceId) {
            // 兼容旧版本：客户端提供ID
            device = this.deviceManager.registerDevice(socket.id, deviceInfo);
            console.log('info', `📱 使用客户端提供的ID注册: ${device?.id || 'unknown'}`);
          } else {
            // 没有ID也没有指纹，服务端生成新ID
            device = this.deviceManager.registerDeviceWithServerGeneratedId(socket.id, deviceInfo);
            console.log('info', `📱 服务端生成新ID注册: ${device?.id || 'unknown'}`);
          }
          
          socket.data.deviceId = device?.id || '';
          socket.data.deviceType = device?.type || 'unknown';
          socket.data.deviceName = device?.name || 'Unknown Device';

          socket.emit('device:registered', {
            success: true,
            deviceId: device?.id || '',
            message: `设备注册成功: ${device?.name || 'Unknown Device'}`
          });

          this.updateConnectedDevicesCount();
          console.log('info', `设备注册成功: ${device?.type || 'unknown'} - ${device?.name || 'Unknown Device'} (${device?.id || 'unknown'})`);
        } catch (error) {
          this.stats.errors++;
          const errorMessage = error instanceof Error ? error.message : 'Unknown error';
          socket.emit('device:registered', {
            success: false,
            deviceId: '',
            message: errorMessage
          });
          console.error('设备注册失败:', errorMessage);
        }
      });

      // 生成配对码
      socket.on('pairing:generate-code', async () => {
        try {
          const deviceId = socket.data.deviceId;
          if (!deviceId) {
            throw new SmartInputError('Device not registered', 'DEVICE_NOT_REGISTERED', 400);
          }

          this.stats.pairingAttempts++;
          const result = await this.pairingManager.generatePairingCode(deviceId);

          socket.emit('pairing:code-generated', result);
          console.log(`配对码生成: ${result.code} for device ${deviceId}`);
        } catch (error) {
          this.stats.errors++;
          const errorMessage = error instanceof Error ? error.message : 'Unknown error';
          socket.emit('pairing:failed', { message: errorMessage });
          console.error('配对码生成失败:', errorMessage);
        }
      });

      // 使用配对码
      socket.on('pairing:use-code', async (data: { code: string }) => {
        try {
          console.log('🔍 [index.ts,socket,pairing:use-code;PAIRING] 使用配对码进行配对: ', data.code);
          const deviceId = socket.data.deviceId;
          if (!deviceId) {
            throw new SmartInputError('Device not registered', 'DEVICE_NOT_REGISTERED', 400);
          }

          const result = await this.pairingManager.usePairingCode(data.code, deviceId);

          if (result.success) {
            this.stats.successfulPairings++;

            // 通知目标设备配对成功
            const targetDevice = this.deviceManager.getDevice(result.deviceId);
            if (targetDevice) {
              this.io.to(targetDevice.socketId).emit('pairing:success', {
                success: true,
                deviceId: deviceId,
                deviceName: socket.data.deviceName || 'Unknown Device'
              });
            }
          }

          socket.emit('pairing:success', result);
          console.log(`配对成功: ${deviceId || 'unknown'} <-> ${result?.deviceId || 'unknown'}`);
        } catch (error) {
          this.stats.errors++;
          const errorMessage = error instanceof Error ? error.message : 'Unknown error';
          socket.emit('pairing:failed', { message: errorMessage });
          console.error('配对失败:', errorMessage);
        }
      });

      // 语音文字发送
      socket.on('voice:send-text', (data: Omit<VoiceTextData, 'timestamp'>) => {
        try {
          const deviceId = socket.data.deviceId;
          if (!deviceId) {
            throw new SmartInputError('Device not registered', 'DEVICE_NOT_REGISTERED', 400);
          }

          const voiceData: VoiceTextData = {
            ...data,
            timestamp: Date.now(),
            deviceId
          };

          // 转发到所有浏览器设备
          const browserDevices = this.deviceManager.getDevicesByType('browser');
          browserDevices.forEach(device => {
            if (device.isOnline && device.capabilities.canReceiveText) {
              this.io.to(device.socketId).emit('voice:text', voiceData);
            }
          });

          this.stats.messagesProcessed++;
          this.stats.lastActivity = Date.now();
          this.deviceManager.updateDeviceActivity(deviceId);

          console.log(`语音文字转发: "${data?.text || ''}" from ${deviceId || 'unknown'} to ${browserDevices?.length || 0} browser(s)`);
        } catch (error) {
          this.stats.errors++;
          const errorMessage = error instanceof Error ? error.message : 'Unknown error';
          socket.emit('voice:error', { message: errorMessage });
          console.error('语音文字发送失败:', errorMessage);
        }
      });

      // 语音识别请求处理
      socket.on('voice:recognize', async (data: {
        audioData: string;
        language: string;
        timestamp: number;
        options?: { provider?: string; format?: string }
      }) => {
        try {
          const deviceId = socket.data.deviceId;
          if (!deviceId) {
            throw new SmartInputError('Device not registered', 'DEVICE_NOT_REGISTERED', 400);
          }

          console.log(`🎤 收到语音识别请求: ${deviceId || 'unknown'}`, {
            language: data?.language || 'unknown',
            provider: data?.options?.provider || 'web',
            audioDataSize: data?.audioData?.length || 0,
            format: data?.options?.format || 'unknown'
          });

          // 创建SpeechService实例（如果还没有）
          if (!this.speechService) {
            this.speechService = new SpeechService();
          }

          // 调用语音识别服务
          const startTime = Date.now();
          const result = await this.speechService.speechToText(data.audioData, {
            provider: data.options?.provider || 'web',
            language: data.language
          });
          const processingTime = Date.now() - startTime;

          console.log(`✅ 语音识别完成: ${result?.text || ''} (耗时: ${processingTime}ms)`);

          // 发送识别结果回客户端
          socket.emit('voice:result', {
            success: true,
            text: result.text,
            confidence: result.confidence,
            provider: result.provider,
            language: result.language,
            processingTime,
            timestamp: Date.now()
          });

          // 同时转发识别结果到浏览器设备
          const voiceData: VoiceTextData = {
            text: result.text,
            confidence: result.confidence,
            language: data.language,
            deviceId,
            timestamp: Date.now(),
            isFinal: true
          };

          // 广播到所有配对的设备
          const pairedDevices = this.pairingManager.getDevicePairingRelationships(deviceId);
          console.log(`🔍 查找设备 ${deviceId || 'unknown'} 的配对关系:`, pairedDevices?.length || 0, '个');

          for (const pairing of pairedDevices) {
            const targetDeviceId = pairing.device1Id === deviceId ? pairing.device2Id : pairing.device1Id;
            console.log(`📤 尝试转发到配对设备: ${targetDeviceId || 'unknown'}`);

            const targetDevice = this.deviceManager.getDevice(targetDeviceId);
            if (targetDevice && targetDevice.socketId) {
              console.log(`✅ 转发语音文本到设备: ${targetDeviceId || 'unknown'} (${targetDevice?.name || 'unknown'})`);
              this.io.to(targetDevice.socketId).emit('voice:text', voiceData);
            } else {
              console.log(`⚠️ 配对设备 ${targetDeviceId || 'unknown'} 不在线或无Socket连接`);
            }
          }

          this.stats.messagesProcessed++;
          this.stats.lastActivity = Date.now();
          this.deviceManager.updateDeviceActivity(deviceId);

          console.log(`🎤 语音识别结果转发到 ${pairedDevices?.length || 0} 个配对设备`);

        } catch (error) {
          this.stats.errors++;
          const errorMessage = error instanceof Error ? error.message : 'Unknown error';

          console.error('❌ 语音识别失败:', errorMessage);

          socket.emit('voice:result', {
            success: false,
            error: errorMessage,
            timestamp: Date.now()
          });
        }
      });

      // 设备列表请求
      socket.on('device:get-list', () => {
        const devices = this.deviceManager.getOnlineDevices().map(device => ({
          id: device.id,
          type: device.type,
          name: device.name,
          capabilities: device.capabilities,
          timestamp: device.timestamp
        }));
        socket.emit('device:list', devices);
      });

      // 使用配对码进行配对
      socket.on('device:pair', async (data: { pairingCode: string }) => {
        console.log('🔍 [socket,device:pair;PAIRING] 使用配对码进行配对: ', data.pairingCode);
        await this.handlePairingRequest({ socket, pairingCode: data.pairingCode });
      });

      // 获取配对状态
      socket.on('device:get-pairing-status', async (data: { deviceId: string }) => {
        try {
          const { deviceId } = data;
          console.log(`🔍 [PAIRING] 查询设备配对状态: ${deviceId || 'unknown'}`);

          try {
            const pairings = this.pairingManager.getDevicePairingRelationships(deviceId);
            console.log(`📊 [PAIRING] 找到 ${pairings?.length || 0} 个配对关系`);

            const pairingStatus = pairings.map(pairing => {
              const otherDeviceId = pairing.device1Id === deviceId ? pairing.device2Id : pairing.device1Id;
              const otherDevice = this.deviceManager.getDevice(otherDeviceId);
              return {
                deviceId: otherDeviceId,
                deviceName: otherDevice?.name || 'Unknown Device',
                deviceType: otherDevice?.type || 'unknown',
                isOnline: otherDevice?.isOnline || false,
                pairedAt: pairing.createdAt
              };
            });

            socket.emit('device:pairing-status', {
              success: true,
              deviceId: deviceId,
              pairings: pairingStatus
            });

            console.log(`✅ [PAIRING] 配对状态查询完成: ${pairingStatus?.length || 0} 个配对`);
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '未知错误';
            console.log(`❌ [PAIRING] 配对状态查询失败: ${errorMessage}`);
            socket.emit('device:pairing-status', {
              success: false,
              deviceId: deviceId,
              error: errorMessage
            });
          }
        } catch (error: any) {
          const errorMessage = error.message || '查询配对状态失败';
          console.log(`❌ [PAIRING] 配对状态查询失败: ${errorMessage}`);
          socket.emit('device:pairing-status', {
            success: false,
            error: errorMessage
          });
        }
      });

      // 心跳检测
      socket.on('system:heartbeat', () => {
        const deviceId = socket.data.deviceId;
        if (deviceId) {
          this.deviceManager.updateDeviceActivity(deviceId);
        }
        socket.emit('connection:status', {
          connected: true,
          timestamp: Date.now()
        });
      });

      // 断开连接
      socket.on('disconnect', (reason) => {
        console.log(`设备断开连接: ${socket?.id || 'unknown'}, 原因: ${reason || 'unknown'}`);

        if (socket.data.deviceId) {
          // this.deviceManager.unregisterDevice(socket.id);
          this.pairingManager.clearDevicePairingCodes(socket.data.deviceId);
          // this.pairingManager.invalidatePairingsForDevice(socket.data.deviceId);
        }

        this.updateConnectedDevicesCount();
      });
    });
  }

  private setupErrorHandlers(): void {
    // 全局错误处理
    process.on('uncaughtException', (error) => {
      console.error('未捕获的异常:', error);
      this.stats.errors++;
    });

    process.on('unhandledRejection', (reason, promise) => {
      console.error('未处理的Promise拒绝:', reason);
      this.stats.errors++;
    });
  }

  private updateConnectedDevicesCount(): void {
    this.stats.connectedDevices = this.deviceManager.getOnlineDevices().length;
  }

  // 混合连接管理器的事件处理方法
  private handleDeviceRegister(data: any): void {
    const { socket, deviceInfo } = data;
    try {
      let device: RegisteredDevice;
      
      if (deviceInfo.hardwareFingerprint) {
        device = this.deviceManager.registerDeviceWithServerGeneratedId(socket.id, deviceInfo);
      } else if (deviceInfo.deviceId) {
        device = this.deviceManager.registerDevice(socket.id, deviceInfo);
      } else {
        device = this.deviceManager.registerDeviceWithServerGeneratedId(socket.id, deviceInfo);
      }
      
      socket.data.deviceId = device?.id || '';
      socket.data.deviceType = device?.type || 'unknown';
      socket.data.deviceName = device?.name || 'Unknown Device';

      // 添加到WebSocket服务
      this.hybridManager.getWebSocketService().addClient(socket.id, device?.id || '', socket);

      // 建立混合连接
      const capabilities = this.detectCapabilities(deviceInfo);
      this.hybridManager.establishConnection(device?.id || '', capabilities);

      socket.emit('device:registered', {
        success: true,
        deviceId: device?.id || '',
        message: `设备注册成功: ${device?.name || 'Unknown Device'}`
      });

      this.updateConnectedDevicesCount();
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      socket.emit('device:registered', {
        success: false,
        deviceId: '',
        message: errorMessage
      });
    }
  }

  private async handleGeneratePairingCode(data: any): Promise<void> {
    const { socket } = data;
    try {
      const deviceId = socket.data.deviceId;
      if (!deviceId) {
        throw new SmartInputError('Device not registered', 'DEVICE_NOT_REGISTERED', 400);
      }

      this.stats.pairingAttempts++;
      const result = await this.pairingManager.generatePairingCode(deviceId);

      socket.emit('pairing:code-generated', result);
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      socket.emit('pairing:failed', { message: errorMessage });
    }
  }

  private async handleUsePairingCode(data: any): Promise<void> {
    const { socket, data: pairingData } = data;
    await this.handlePairingRequest({ socket, code: pairingData.code });
  }

  private handleVoiceSendText(data: any): void {
    const { socket, data: voiceData } = data;
    try {
      const deviceId = socket.data.deviceId;
      if (!deviceId) {
        throw new SmartInputError('Device not registered', 'DEVICE_NOT_REGISTERED', 400);
      }

      const textData: VoiceTextData = {
        ...voiceData,
        timestamp: Date.now(),
        deviceId
      };

      // 转发到所有浏览器设备
      const browserDevices = this.deviceManager.getDevicesByType('browser');
      browserDevices.forEach(device => {
        if (device.isOnline && device.capabilities.canReceiveText) {
          this.hybridManager.sendMessage({
            id: this.generateMessageId(),
            type: 'voice:text',
            data: textData,
            timestamp: Date.now(),
            source: 'websocket',
            target: device.id
          });
        }
      });

      this.stats.messagesProcessed++;
      this.stats.lastActivity = Date.now();
      this.deviceManager.updateDeviceActivity(deviceId);
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      socket.emit('voice:error', { message: errorMessage });
    }
  }

  private handleVoiceRecognize(data: any): void {
    const { socket, data: voiceData } = data;
    try {
      const deviceId = socket.data.deviceId;
      if (!deviceId) {
        throw new SmartInputError('Device not registered', 'DEVICE_NOT_REGISTERED', 400);
      }

      if (!this.speechService) {
        this.speechService = new SpeechService();
      }

      const startTime = Date.now();
      this.speechService.speechToText(voiceData.audioData, {
        provider: voiceData.options?.provider || 'web',
        language: voiceData.language
      }).then((result: any) => {
        const processingTime = Date.now() - startTime;

        // 发送识别结果回客户端
        socket.emit('voice:result', {
          success: true,
          text: result.text,
          confidence: result.confidence,
          provider: result.provider,
          language: result.language,
          processingTime,
          timestamp: Date.now()
        });

        // 转发识别结果到配对设备
        const pairedDevices = this.pairingManager.getDevicePairingRelationships(deviceId);
        for (const pairing of pairedDevices) {
          const targetDeviceId = pairing.device1Id === deviceId ? pairing.device2Id : pairing.device1Id;
          
          this.hybridManager.sendMessage({
            id: this.generateMessageId(),
            type: 'voice:text',
            data: {
              text: result.text,
              confidence: result.confidence,
              language: voiceData.language,
              deviceId,
              timestamp: Date.now(),
              isFinal: true
            },
            timestamp: Date.now(),
            source: 'websocket',
            target: targetDeviceId
          });
        }

        this.stats.messagesProcessed++;
        this.stats.lastActivity = Date.now();
        this.deviceManager.updateDeviceActivity(deviceId);
      }).catch((error: any) => {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        socket.emit('voice:result', {
          success: false,
          error: errorMessage,
          timestamp: Date.now()
        });
      });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      socket.emit('voice:result', {
        success: false,
        error: errorMessage,
        timestamp: Date.now()
      });
    }
  }

  private handleVoiceStreamStart(data: any): void {
    const { socket, params } = data;
    console.log('流式语音开始:', socket.data.deviceId, params);
  }

  private handleVoiceStreamData(data: any): void {
    const { socket, audioChunk } = data;
    console.log('流式语音数据:', socket.data.deviceId, audioChunk.length);
  }

  private handleVoiceStreamEnd(data: any): void {
    const { socket } = data;
    console.log('流式语音结束:', socket.data.deviceId);
  }

  private handleGetDeviceList(data: any): void {
    const { socket } = data;
    const devices = this.deviceManager.getOnlineDevices().map(device => ({
      id: device.id,
      type: device.type,
      name: device.name,
      capabilities: device.capabilities,
      timestamp: device.timestamp
    }));
    socket.emit('device:list', devices);
  }

  private async handleDevicePair(data: any): Promise<void> {
    const { socket, data: pairingData } = data;
    await this.handlePairingRequest({ socket, pairingCode: pairingData.pairingCode });
  }

  private handleGetPairingStatus(data: any): void {
    const { socket, data: statusData } = data;
    try {
      const pairings = this.pairingManager.getDevicePairingRelationships(statusData.deviceId);
      socket.emit('device:pairing-status', {
        success: true,
        deviceId: statusData.deviceId,
        pairings: pairings
      });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      socket.emit('device:pairing-status', {
        success: false,
        deviceId: statusData.deviceId,
        error: errorMessage
      });
    }
  }

  private detectCapabilities(deviceInfo: any): string[] {
    const capabilities = [];
    
    if (deviceInfo.type === 'mobile') {
      capabilities.push('mobile');
      capabilities.push('voice-streaming');
    }
    
    if (deviceInfo.type === 'browser') {
      capabilities.push('browser-extension');
    }
    
    if (deviceInfo.type === 'desktop') {
      capabilities.push('desktop');
      capabilities.push('voice-streaming');
    }
    
    return capabilities;
  }

  private generateMessageId(): string {
    return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * 统一处理配对请求（所有API/Socket/Hybrid入口都调用此方法）
   */
  private async handlePairingRequest({ socket, code, pairingCode, deviceId }: { socket: any, code?: string, pairingCode?: string, deviceId?: string }) {
    const pairing_code = (code || pairingCode) ?? '';
    const requestingDeviceId = deviceId || socket?.data?.deviceId;
    if (!requestingDeviceId) {
      if (socket) socket.emit('device:pair:result', { success: false, error: '设备未注册' });
      return { success: false, error: '设备未注册' };
    }
    // 幂等锁key
    const lockKey = `${requestingDeviceId}:${pairing_code}`;
    const now = Date.now();
    // 5秒内同一设备+配对码只处理一次
    if (this.pairingRequestLocks.has(lockKey) && now - this.pairingRequestLocks.get(lockKey)! < 5000) {
      if (socket) socket.emit('device:pair:result', { success: false, error: '重复配对请求，请稍后重试' });
      return { success: false, error: '重复配对请求，请稍后重试' };
    }
    this.pairingRequestLocks.set(lockKey, now);
    // 清理过期锁
    for (const [k, t] of this.pairingRequestLocks.entries()) {
      if (now - t > 10000) this.pairingRequestLocks.delete(k);
    }
    try {
      const result = await this.pairingManager.usePairingCode(pairing_code, requestingDeviceId);
      if (socket) {
        socket.emit('device:pair:result', {
          success: true,
          deviceId: result.deviceId,
          deviceName: result.deviceName
        });
      }
      const targetDevice = this.deviceManager.getDevice(result.deviceId);
      if (targetDevice && targetDevice.socketId && socket) {
        const requestingDevice = this.deviceManager.getDevice(requestingDeviceId);
        this.io.to(targetDevice.socketId).emit('device:paired', {
          success: true,
          deviceId: requestingDeviceId,
          deviceName: requestingDevice?.name || '未知设备'
        });
      }
      return { ...result };
    } catch (error: any) {
      const errorMessage = error.message || '配对失败';
      if (socket) socket.emit('device:pair:result', { success: false, error: errorMessage });
      return { success: false, error: errorMessage };
    }
  }

  public start(): void {
    this.server.listen(config.port, config.host, () => {
      const projectRoot = process.cwd().includes('/server') ? process.cwd().replace('/server', '') : process.cwd();
      const certPath = path.join(projectRoot, 'certs', 'cert.pem');
      const keyPath = path.join(projectRoot, 'certs', 'key.pem');
      const useHttps = fs.existsSync(certPath) && fs.existsSync(keyPath);
      const protocol = useHttps ? 'https' : 'http';

      console.log(`SmartInput 服务器启动成功`);
      console.log(`地址: ${protocol}://${config.host}:${config.port}`);
      console.log(`环境: ${process.env.NODE_ENV || 'development'}`);
      console.log(`时间: ${new Date().toISOString()}`);
    });
  }

  public stop(): Promise<void> {
    return new Promise((resolve) => {
      console.log('正在关闭服务器...');

      // 清理资源
      try {
        if (this.deviceManager && typeof this.deviceManager.destroy === 'function') {
          this.deviceManager.destroy();
        }
        if (this.pairingManager && typeof this.pairingManager.destroy === 'function') {
          this.pairingManager.destroy();
        }
      } catch (error) {
        console.error('关闭服务器时出错:', error);
      }

      this.server.close(() => {
        console.log('服务器已关闭');
        resolve();
      });
    });
  }
}

// 启动服务器
const server = new SmartInputServer();
server.start();

// 优雅关闭
const gracefulShutdown = async (signal: string) => {
  console.log(`收到 ${signal} 信号，正在关闭服务器...`);
  try {
    await server.stop();
    process.exit(0);
  } catch (error) {
    console.error('关闭服务器时出错:', error);
    process.exit(1);
  }
};

process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));

export default SmartInputServer;